package com.ruoyi.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

@Configuration
public class MqttConfig {

    @Value("${mqtt.server}")
    private String mqttServer;
    @Value("${mqtt.username}")
    private String username;
    @Value("${mqtt.password}")
    private String password;
    @Value("${mqtt.client-id}")
    private String clientId;
    @Value("${mqtt.timeout}")
    private int timeout;
    @Value("${mqtt.keep-alive}")
    private int keepAlive;

    // 配置 MQTT 连接选项
    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepAlive);
        options.setCleanSession(true); // 是否清除会话（false 为持久化连接）
        return options;
    }

    // 创建 MQTT 客户端 Bean
    @Bean
    public MqttClient mqttClient(MqttConnectOptions options) throws Exception {
        Random random = new Random();
        int randomNumber = random.nextInt();  // 随机整数
        MqttClient client = new MqttClient(mqttServer, clientId+randomNumber);
        client.connect(options);
        System.out.println("MQTT 客户端已连接到服务器：" + mqttServer); // 添加日志输出
        return client;
    }

}